const BASE_URL = 'http://api.yanzhihu.top/v1.0';
export const USER_URL = BASE_URL.replace('/v1.0','') + '/view/service.html';
export const PRIVACY_URL = BASE_URL.replace('/v1.0','') + '/view/privacy.html';

function getNoEmptyProps(obj){
	if(!obj) return ''
	const newObj = Object.entries(obj).reduce((acc, [key, value]) => {
		if (value !== undefined && value !== '') {
			acc[key] = value;
		}
		return acc;
	}, {});
	if(JSON.stringify(newObj) == '{}'){
		return ''
	} else {
		const str = Object.entries(newObj).map(([key, value]) => `${key}=${value}`).join('&')
		return `?${str}`
	} 
}


var tokenData;
var tokenGetTime;

export async function getToken() {
    if (!tokenData || ((new Date().getTime() - tokenGetTime)/1000 >= (tokenData.expires - 60))) {
        return new Promise((resolve, reject) => {
            uni.request({
                url: BASE_URL + '/account/gettoken',
                method: "POST",
                header: {
                    'Content-Type': "application/json"
                },
                data: {
                    UserName: 'moliang',
                    password: "moliang31415926="
                },
                success: function (res) {
					/* uni.showToast({
						title:JSON.stringify(res),
						icon:'none'
					}) */
                    tokenData = res.data.data;
                    if (res.statusCode !== 200) {
                        return reject()
                    }
					tokenGetTime = new Date().getTime();
                    return resolve(res.data.data)
                },
                fail: rej => {
					uni.showToast({
						title:JSON.stringify(rej),
						icon:'none'
					})
					return reject();
                }
            });
        });
    } else {
        return new Promise((resolve, reject) => {
            return resolve(tokenData);
        });
    }
}

async function http(url, method, params, list = false) {
	const {type, token} = await getToken();
	const trueUrl = method.toUpperCase() === 'GET' ? url + getNoEmptyProps(params) : url
	return new Promise((resolve, reject) => {
		uni.request({
			url:BASE_URL + trueUrl,
			method:method,
			data: method.toUpperCase() == 'POST' ? params : {},
			header: {
			    'Content-Type': "application/json",
			    "Authorization": `${type} ${token}`,
			},
			success(res) {
				if (res.statusCode !== 200 || res.data.status !== 0) {
				    return reject(res.data?.msg || '调用接口失败')
				}
				return resolve(list ? res.data : res.data.data)
			},
			fail:rej => {
				reject(rej?.errMsg || rej)
			}
		})
	}).then(res => [res,null]).catch(err => [null,err]);
}

//获取app最新版本
export async function updateVersion(ver) {
	return http('/common/updateversion','GET',{ver})
}

//登录
export async function login(userName,password){
	return http('/account/login','POST',{userName,password})
}

//验证码登录
export async function loginByCode(userName,verifyCode) {
	return http('/account/loginbyverify','POST',{userName,verifyCode})
}

//注册
export async function register(params) {
	return http('/account/adduser','POST',params)
}

//发送验证码
export async function sendSms(mobile,type) {
	return http('/account/sendsms','POST',{mobile,type})
}

//找回密码
export async function findPwd(params) {
	return http('/account/resetpassword','POST',params)
}

//修改密码
export async function changePwd(params) {
	return http('/account/setpassword','POST',params)
}

//获取个人信息
export async function getUserInfo(userId) {
	return http('/account/getuserinfo','GET', {userId})
}

//获取邀请二维码
export async function getQrCode(userId) {
	return http('/qrcode/getinviteqrcode','GET',{userId})
}

//获取收款码
export async function getPayCode(userId) {
	return http('/qrcode/getpayqrcode','GET',{userId})
}

//通过邀请码获取手机号
export async function getPhoneByCode(code) {
	return http('/account/getphone','GET',{code})
}

//获取子账号
export async function getChildList(userId) {
	return http(`/user/getchildlist/${userId}`,'GET')
}

//通过form表单上传头像
export async function uploadImg(url) {
	const { token, type } = await getToken();
	return new Promise((resolve, reject) => {
	    uni.uploadFile({
	        url: BASE_URL + `/common/uploadavatar`,
	        header: {
	            "Authorization": `${type} ${token}`
	        },
	        filePath: url,
	        name: 'file',
	        formData: {
	        },
	        success: (res) => {
	            if (res.statusCode !== 200) {
	                return reject(res.data?.msg || '上传失败')
	            }
	            return resolve(res.data)
	        },
			fail:rej => {
				reject(rej?.errMsg || rej)
			}
	    });
	}).then(res => [res,null]).catch(err => [null,err]);
}

//修改个人信息
export async function updateInfo(userId, params) {
	return http(`/user/updateinfo/${userId}`, 'POST', params);
}

//首页轮播图
export async function getAdList() {
	return http(`/common/getadvlist`, 'GET');
}

//轮播图内容
export async function getAdDetail(id) {
	return http(`/common/getadvdetail/${id}`, 'GET')
}

//首页商品列表
export async function getHomeGoods(categoryId) {
	return http(`/home/getproductlist/${categoryId}`,'GET')
}

//商品详情
export async function getGoodsDetail(ProductID) {
	return http(`/home/getproductdetail/${ProductID}`,'GET')
}


//我的团队
export async function getTeamList(userId) {
	return http(`/user/getteamlist/${userId}`,'GET',null,true)
}

//财务管理
export async function getAmountList(userId,params) {
	return http(`/user/getamountlist/${userId}`,'GET',params,true)
}

//待释放积分
export async function getReleaseList(userId,params) {
	return http(`/user/getreleaselist/${userId}`,'GET',params,true)
}

//收货地址列表
export async function getAddressList(userId) {
	return http(`/user/getaddresslist/${userId}`,'GET')
}

//获取所有区域
export async function getAreaJson() {
	return http(`/common/getareajson`,'GET')
}

//充值登记
export async function recharge(userId, params) {
	return http(`/user/recharge/${userId}`,'POST',params)
}

//添加或者修改地址
export async function addAddress(userId, params) {
	return http(`/user/addaddress/${userId}`,'POST',params)
}

//删除收货地址
export async function delAddress(userId, addressId){
	return http(`/user/deladdress/${userId}/${addressId}`,'POST')
}

//获取默认地址
export async function getDefaultAddress(userId) {
	return http(`/user/getdefaultaddress/${userId}`,'GET')
}

//获取银行卡信息
export async function getBankInfo(userId){
	return http(`/user/getbankinfo/${userId}`,'GET')
}

//修改银行卡信息
export async function addBank(userId,params) {
	return http(`/user/addbank/${userId}`,'POST',params)
}

//三个功能开关
export async function getFunction() {
	return http(`/user/getfunction`,'GET')
}

//消费积分互转
export async function bonusTransfer(userId, params) {
	return http(`/user/bonustransfer/${userId}`,'POST',params)
}

//绿色积分兑换
export async function bonusExchange(userId,amount) {
	return http(`/user/bonusexchange/${userId}`,'POST',{amount})
}


//生成订单
export async function createOrder(userId, params) {
	return http(`/home/createorder/${userId}`,'POST',params)
}

//订单列表
export async function orderList(userId,params) {
	return http(`/user/getorderlist/${userId}`,'GET',params,true)
}

//订单详情
export async function orderDetail(userId, orderId) {
	return http(`/user/getorderdetail/${userId}/${orderId}`,'GET')
}

//取消订单
export async function cancelOrder(userId, orderId) {
	return http(`/user/cancelorder/${userId}/${orderId}`,'POST')
}

//确认收货
export async function finishOrder(userId, orderId) {
	return http(`/user/finishorder/${userId}/${orderId}`,'POST')
}

//查看物流
export async function logisticsInfo(userId, orderId) {
	return http(`/user/logisticsinfo/${userId}/${orderId}`,'GET')
}

//付款
export async function pay(userId,orderId) {
	return http(`/payment/pay/${userId}/${orderId}`,'POST')
}